<?php
namespace aszx0413\yii2gii;

class Sql
{

    public static function common1(Table $table)
    {
        $sql = '';

        // COMMENT
        $sql .= "# {$table->nameCn}" . "\n";

        // DROP TABLE
        $sql .= "DROP TABLE IF EXISTS `{$table->name}`;" . "\n";

        // CREATE TABLE START
        $sql .= "CREATE TABLE `{$table->name}` (" . "\n";
        $sql .= "\t" . "`id`         INT(10) NOT NULL AUTO_INCREMENT," . "\n";
        $sql .= "\t" . "`created_at` DATETIME NOT NULL DEFAULT NOW()," . "\n";
        $sql .= "\t" . "`updated_at` DATETIME NULL," . "\n";
        $sql .= "\t" . "`status`     TINYINT(1) NOT NULL DEFAULT 1," . "\n";
        $sql .= "\n";

        return $sql;
    }

    public static function field(Field $field)
    {
        $sql = '';

        // tab
        $sql .= "\t";

        // column name
        $sql .= str_pad("`{$field->name}`", 20);

        // type and length
        if ($field->length) {
            $sql .= ' ' . str_pad("{$field->type}({$field->length})", 13);
        } else {
            // DATETIME etc.
            $sql .= ' ' . str_pad("{$field->type}", 13);
        }

        // NOT NULL
        $sql .= " NULL";

        // DEFAULT
        // if there is INT, regardless INT/TINYINT/MEDIUMINT/BIGINT,
        // then it should be default 0
        if (strpos($field->type, 'INT') !== false) {
            $sql .= " DEFAULT 0           ";
        } elseif ($field->type == 'VARCHAR') {
            $sql .= " DEFAULT ''          ";
        } elseif ($field->type == 'TEXT') {
            $sql .= "                     ";
        } elseif ($field->type == 'DATETIME') {
            $sql .= "                     ";
        } elseif ($field->type == 'DECIMAL') {
            $sql .= " DEFAULT 0           ";
        }

        // COMMENT
        $sql .= " COMMENT '{$field->nameCn}'";

        $sql .= "," . "\n";

        return $sql;
    }

    public static function common2(Table $table)
    {
        $sql = "\n";

        // PRIMARY KEY
        $sql .= "\t" . "PRIMARY KEY(`id`)" . "\n";

        // ENGINE=InnoDB MyISAM
        $sql .= ") ENGINE=InnoDb CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '{$table->nameCn}';" . "\n\n\n";

        return $sql;
    }
}
